package com.lxf.test.androidtest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.lxf.test.androidtest.abc.MainActivity;
import com.lxf.test.androidtest.abc.MyDBHelper;
import com.lxf.test.androidtest.charts.BarChartActivity;
import com.lxf.test.androidtest.main.MenuActivity;

import java.io.File;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;


/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class FullscreenActivity extends Activity {
    private static final boolean AUTO_HIDE = true;

    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();
    private View mContentView;
    private Button btn_test1;
    private Button btn_test2;
    private Button btn_imp;
    private Button btn_toCharts;
    private TextView text1;

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };
    private View mControlsView;
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
        }
    };
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_fullscreen);

        mVisible = true;
        mControlsView = findViewById(R.id.fullscreen_content_controls);
        mContentView = findViewById(R.id.fullscreen_content);

        // Set up the user interaction to manually show or hide the system UI.
        mContentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toggle();
            }
        });

        findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener);

        initCom();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

        Intent intent = new Intent();
        intent.setClass(FullscreenActivity.this, MenuActivity.class);
        startActivity(intent);
        finish();
    }

    protected void initCom() {
        btn_test1 = (Button) findViewById(R.id.btn_test1);
        btn_test1.setOnClickListener(new Btn11Listener());

        btn_test2 = (Button) findViewById(R.id.btn_test2);
        btn_test2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(FullscreenActivity.this, BarChartActivity.class);
                startActivity(intent);
            }
        });

        btn_imp = (Button) findViewById(R.id.btn_imp);

        btn_imp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 1);
            }
        });

        btn_toCharts = (Button) findViewById(R.id.btn_toCharts);
        btn_toCharts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyDBHelper dbHelper = new MyDBHelper(FullscreenActivity.this, "stu_db", null, 1);
                SQLiteDatabase db = dbHelper.getReadableDatabase();
//                String sql = "create table TASKFINISH( ID VARCHAR(32) not null,employeeid VARCHAR(32),taskuid VARCHAR(32)," +
//                        "workdate DATE,completeqty INT, runtime1 INT, completework1 INT, actualwork,INT)";
//                sql = "drop table TASKFINISH";
//                db.execSQL(sql);
//                System.out.println("db delete ok");

                String str = "";
                Cursor cursor = db.query("TASKFINISH", new String[]{"ID", "employeeid","workdate", "completework1", "actualwork"}, null, null, null, null, null);
                while (cursor.moveToNext()) {
                    String id = cursor.getString(cursor.getColumnIndex("ID"));
                    String age = cursor.getString(cursor.getColumnIndex("employeeid"));
                    String workdate = cursor.getString(cursor.getColumnIndex("workdate"));
                    int completework = cursor.getInt(cursor.getColumnIndex("completework1"));
                    System.out.println(completework);
                    int actualwork = cursor.getInt(cursor.getColumnIndex("actualwork"));
                    str+= "id：" + id + " 日期：" + workdate + " 计划：" + completework +" 实际:"+actualwork+"\n";
                }
                System.out.println(str);
                text1.setText(str);
            }
        });

        text1 = (TextView) findViewById(R.id.text1);
    }

    //选择文件后的回调函数
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {//是否选择，没选择就不会继续
            Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
            String path = uri.getPath();
            System.out.print("test getpath:" + path);
            addData(path);
            Toast.makeText(FullscreenActivity.this, path, Toast.LENGTH_SHORT).show();
        }
    }

    public void addData(String path) {
        try{
            Workbook book = Workbook.getWorkbook(new File(path));
            MyDBHelper dbHelper = new MyDBHelper(FullscreenActivity.this, "stu_db", null, 1);
            SQLiteDatabase db = dbHelper.getWritableDatabase();

//           String sql = "create table TASKFINISH( ID VARCHAR(32) not null,employeeid VARCHAR(32),taskuid VARCHAR(32)," +
//                    "workdate DATE,completeqty INT, runtime1 INT, completework1 INT, actualwork,INT)";
//            //sql = "delete from TASKFINISH";
//            db.execSQL(sql);

//            String tbnames = "";
//            Cursor cursor = db.query("sqlite_master", new String[]{"tbl_name" }, "type=?", new String[]{"table"}, null, null, null);
//            while(cursor.moveToNext()){
//                String tbname = cursor.getString(cursor.getColumnIndex("tbl_name"));
//                tbnames += tbname+";";
//            }
//            System.out.println("testsql:"+tbnames);

            System.out.println(">>>>>>number of sheet " + book.getNumberOfSheets());
            // 获得第4个工作表对象,测试
            Sheet sheet = book.getSheet(3);
            Cell cell = null;
            int Rows = sheet.getRows();
            int Cols = sheet.getColumns();
            System.out.println("当前工作表的名字:" + sheet.getName());
            System.out.println("总行数:" + Rows);
            System.out.println("总列数:" + Cols);
            String str = "";
            String temp2 = "";
            for (int i = 0; i < Rows; ++i) {
                ContentValues cv = new ContentValues();
                if(i>=2){//第三行开始
                    for (int j = 0; j < Cols; ++j) {
                        //列
                        String col = (sheet.getCell(j, 0)).getContents();
                        //列的类型
                        String type = (sheet.getCell(j, 1)).getContents();
                        cell = sheet.getCell(j, i);

//                        if(type.equals("varchar2")){
//                            cv.put(col,cell.getContents());
//                        }else if(type.equals("integer")){
//                            cv.put(col,((NumberCell) cell).getValue());
//                        }else if(type.equals("date")){
//                            cv.put(col,cell.getContents());
//                        }
                        cv.put(col,cell.getContents());
                        System.out.print((sheet.getCell(j, i)).getContents() + "\t");
                    }
                    long a = db.insert("TASKFINISH", null, cv);
                    System.out.println("yyyyyyyyy:"+a);
                }
                System.out.print("\n");
            }
            db.close();
            book.close();

//            Cursor cursor = db.query("TASKFINISH", new String[]{"id", "employeeid","workdate", "completework", "actualwork"}, null, null, null, null, null);
//            while (cursor.moveToNext()) {
//                String id = cursor.getString(cursor.getColumnIndex("id"));
//                String age = cursor.getString(cursor.getColumnIndex("employeeid"));
//                String workdate = cursor.getString(cursor.getColumnIndex("workdate"));
//                int completework = cursor.getInt(cursor.getColumnIndex("completework"));
//                int actualwork = cursor.getInt(cursor.getColumnIndex("actualwork"));
//                System.out.println("query-------> id：" + id + " 日期：" + workdate + " 计划：" + completework +" 实际:"+actualwork+"\n");
//                //Toast.makeText(getApplicationContext(), "query------->" + "姓名：" + name + " " + "年龄：" + age + " " + "性别：" + sex, Toast.LENGTH_SHORT).show();
//            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }



    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
    }

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        mVisible = true;

        // Schedule a runnable to display UI elements after a delay
        mHideHandler.removeCallbacks(mHidePart2Runnable);
        mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
    }

    /**
     * Schedules a call to hide() in [delay] milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Fullscreen Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.lxf.test.androidtest/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Fullscreen Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.lxf.test.androidtest/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }

class Btn11Listener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClass(FullscreenActivity.this, MainActivity.class);
            startActivity(intent);
        }
    }

}
